/**
 * 忘记密码页面组件
 * 提供用户重置密码的功能，包括：
 * - 用户名和手机号验证
 * - 验证码发送和验证
 * - 新密码设置和确认
 * - 响应式布局支持
 */

<template>
  <div class="forgot-password-container">
    <div class="login-box">
      <!-- 左侧品牌展示区域 -->
      <div class="login-left">
        <div class="brand">
          <div class="logo">EDU</div>
          <h1>教育共享平台</h1>
          <p class="slogan">让知识触手可及</p>
        </div>
        <div class="decoration">
          <div class="vase-image">
            <img v-if="avatarUrl" :src="avatarUrl" alt="用户头像" class="user-avatar-preview">
            <div v-else class="default-avatar-preview">
              <svg xmlns="http://www.w3.org/2000/svg" width="80" height="80" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">
                <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path>
                <circle cx="12" cy="7" r="4"></circle>
              </svg>
            </div>
          </div>
          <div class="stats-card">
            <div class="stat-item">
              <h3>5.8</h3>
            </div>
            <div class="stat-item">
              <h3>99+</h3>
            </div>
            <div class="stat-item">
              <h3>110K</h3>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧表单区域 -->
      <div class="login-right">
        <div class="login-header">
          <h2>重置密码</h2>
          <p>请填写以下信息重置您的密码</p>
        </div>
        <form class="login-form" @submit.prevent="handleSubmit">
          <!-- 用户名输入 -->
          <div class="form-group">
            <div class="input-group">
              <div class="input-icon">
                <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                  <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path>
                  <circle cx="12" cy="7" r="4"></circle>
                </svg>
              </div>
              <input 
                type="text" 
                v-model="formData.userName" 
                placeholder="请输入用户名"
                required
                @input="handleUserNameInput"
              >
            </div>
          </div>

          <!-- 手机号输入 -->
          <div class="form-group">
            <div class="input-group">
              <div class="input-icon">
                <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                  <path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"></path>
                </svg>
              </div>
              <input 
                type="text" 
                v-model="formData.mobile" 
                placeholder="请输入手机号"
                @blur="validateMobile"
                required
              >
            </div>
            <span class="error-message" v-if="mobileError">{{ mobileError }}</span>
          </div>

          <!-- 验证码输入 -->
          <div class="form-group">
            <div class="input-group code-group">
              <div class="input-icon">
                <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                  <rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect>
                  <path d="M7 11V7a5 5 0 0 1 10 0v4"></path>
                </svg>
              </div>
              <input 
                type="text" 
                v-model="formData.verificationCode" 
                placeholder="请输入验证码"
                required
              >
              <button 
                type="button" 
                class="code-btn" 
                :disabled="isCountDown || !isMobileValid" 
                @click="sendCode"
              >
                {{ countDownText }}
              </button>
            </div>
          </div>

          <!-- 新密码输入 -->
          <div class="form-group">
            <div class="input-group">
              <div class="input-icon">
                <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                  <rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect>
                  <path d="M7 11V7a5 5 0 0 1 10 0v4"></path>
                </svg>
              </div>
              <input 
                type="password" 
                v-model="formData.password" 
                placeholder="密码（必须包含字母和数字，不少于6位）"
                @focus="showPasswordTip = true"
                @blur="showPasswordTip = false"
                required
              >
            </div>
            <div class="password-tip" v-show="showPasswordTip">
              <p>密码要求：</p>
              <ul>
                <li :class="{ valid: hasNumber }">✓ 包含数字</li>
                <li :class="{ valid: hasLetter }">✓ 包含字母</li>
                <li :class="{ valid: isLongEnough }">✓ 长度不少于6位</li>
              </ul>
            </div>
          </div>

          <!-- 确认密码输入 -->
          <div class="form-group">
            <div class="input-group">
              <div class="input-icon">
                <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                  <rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect>
                  <path d="M7 11V7a5 5 0 0 1 10 0v4"></path>
                </svg>
              </div>
              <input 
                type="password" 
                v-model="formData.confirmPassword" 
                placeholder="确认密码"
                required
              >
            </div>
          </div>

          <!-- 提交按钮 -->
          <div class="form-group">
            <button type="submit" :disabled="loading" class="submit-btn">
              <span class="btn-text">{{ loading ? '提交中...' : '重置密码' }}</span>
            </button>
          </div>

          <!-- 返回登录链接 -->
          <div class="bottom-links">
            <router-link to="/login" class="back-link">返回登录</router-link>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { sendResetPasswordSmsCode, checkResetPasswordSmsCode, resetPassword, getUserAvatarByName } from '@/api/user'

export default {
  name: 'ForgotPasswordView',
  
  setup() {
    const router = useRouter()
    
    // 表单数据
    const formData = reactive({
      userName: '',
      mobile: '',
      verificationCode: '',
      password: '',
      confirmPassword: ''
    })

    // 状态变量
    const loading = ref(false) // 提交按钮加载状态
    const isCountDown = ref(false) // 验证码倒计时状态
    const countDownText = ref('获取验证码') // 验证码按钮文本
    const mobileError = ref('') // 手机号错误信息
    const isMobileValid = ref(false) // 手机号验证状态
    const showPasswordTip = ref(false) // 密码提示显示状态
    const avatarUrl = ref('') // 用户头像URL
    const avatarTimer = ref(null) // 用于防抖的定时器

    // 密码验证计算属性
    const hasNumber = computed(() => {
      return /\d/.test(formData.password)
    })

    const hasLetter = computed(() => {
      return /[a-zA-Z]/.test(formData.password)
    })

    const isLongEnough = computed(() => {
      return formData.password.length >= 6
    })

    const isPasswordValid = computed(() => {
      return hasNumber.value && hasLetter.value && isLongEnough.value
    })

    // 获取用户头像的函数
    const fetchUserAvatar = async (username) => {
      try {
        const avatar = await getUserAvatarByName(username)
        avatarUrl.value = avatar
      } catch (error) {
        // 获取头像失败时，使用默认头像
        avatarUrl.value = ''
      }
    }

    // 处理用户名输入，获取头像
    const handleUserNameInput = () => {
      // 清除之前的定时器
      if (avatarTimer.value) {
        clearTimeout(avatarTimer.value)
      }
      
      const username = formData.userName.trim()
      if (username) {
        // 设置新的定时器，500ms 后执行
        avatarTimer.value = setTimeout(() => {
          fetchUserAvatar(username)
        }, 500)
      } else {
        avatarUrl.value = ''
      }
    }

    /**
     * 验证手机号格式
     * 检查手机号是否为空和格式是否正确
     */
    const validateMobile = () => {
      const mobileRegex = /^1[3-9]\d{9}$/
      if (!formData.mobile) {
        mobileError.value = '请输入手机号'
        isMobileValid.value = false
      } else if (!mobileRegex.test(formData.mobile)) {
        mobileError.value = '请输入正确的手机号'
        isMobileValid.value = false
      } else {
        mobileError.value = ''
        isMobileValid.value = true
      }
    }

    /**
     * 开始验证码倒计时
     * 设置60秒倒计时，更新按钮状态和文本
     */
    const startCountDown = () => {
      isCountDown.value = true
      let count = 60
      countDownText.value = `${count}秒后重试`
      const timer = setInterval(() => {
        count--
        countDownText.value = `${count}秒后重试`
        if (count <= 0) {
          clearInterval(timer)
          isCountDown.value = false
          countDownText.value = '获取验证码'
        }
      }, 1000)
    }

    /**
     * 发送验证码
     * 验证手机号并发送验证码请求
     */
    const sendCode = async () => {
      try {
        validateMobile()
        if (!isMobileValid.value) return

        const response = await sendResetPasswordSmsCode(formData.mobile)
        
        if (response.code === 200) {
          startCountDown()
        } else {
          ElMessage.error(response.message || '验证码发送失败')
        }
      } catch (error) {
        ElMessage.error('发送验证码失败，请稍后重试')
      }
    }

    /**
     * 处理表单提交
     * 验证表单数据并发送重置密码请求
     */
    const handleSubmit = async () => {
      try {
        if (!isPasswordValid.value) {
          ElMessage.error('密码必须包含字母和数字，且不少于6位')
          return
        }

        if (formData.password !== formData.confirmPassword) {
          ElMessage.error('两次输入的密码不一致')
          return
        }

        const checkResponse = await checkResetPasswordSmsCode(formData.mobile, formData.verificationCode)

        if (checkResponse.code !== 200) {
          ElMessage.error('验证码错误')
          return
        }

        loading.value = true
        const response = await resetPassword({
          userName: formData.userName,
          mobile: formData.mobile,
          password: formData.password
        })

        if (response.code === 200) {
          ElMessage.success('密码重置成功')
          router.push('/login')
        } else {
          ElMessage.error(response.message || '密码重置失败')
        }
      } catch (error) {
        ElMessage.error('重置密码失败，请稍后重试')
      } finally {
        loading.value = false
      }
    }

    return {
      formData,
      loading,
      isCountDown,
      countDownText,
      mobileError,
      isMobileValid,
      validateMobile,
      sendCode,
      handleSubmit,
      showPasswordTip,
      hasNumber,
      hasLetter,
      isLongEnough,
      isPasswordValid,
      avatarUrl,
      avatarTimer,
      handleUserNameInput
    }
  }
}
</script>

<style scoped>
.forgot-password-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: #fff;
  padding: 20px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  overflow-y: auto;
}

.login-box {
  display: flex;
  background: #fff;
  border-radius: 24px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.05);
  width: 1200px;
  min-height: 700px;
  overflow: hidden;
}

.login-left {
  flex: 1.2;
  background: #e9ecef;
  padding: 60px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  position: relative;
}

.decoration {
  position: relative;
  height: 400px;
  margin-top: 40px;
}

.vase-image {
  width: 200px;
  height: 200px;
  position: absolute;
  left: 40px;
  bottom: 100px;
  border-radius: 50%;
  overflow: hidden;
  background: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.user-avatar-preview {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.default-avatar-preview {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
}

.default-avatar-preview svg {
  width: 80px;
  height: 80px;
  color: #c0c4cc;
}

.vase-image:hover {
  transform: translateY(-5px);
  box-shadow: 0 12px 32px rgba(0, 0, 0, 0.15);
}

.stats-card {
  position: absolute;
  right: 20px;
  bottom: 40px;
  background: white;
  padding: 30px;
  border-radius: 24px;
  display: flex;
  gap: 40px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
}

.stat-item h3 {
  color: #343a40;
  font-size: 1.5rem;
  font-weight: 600;
}

.login-right {
  flex: 1;
  padding: 60px 80px;
  background: white;
}

.login-header {
  margin-bottom: 3rem;
}

.login-header h2 {
  color: #1f2937;
  font-size: 2.5rem;
  margin-bottom: 1rem;
  font-weight: 600;
}

.login-header p {
  color: #6b7280;
  font-size: 1.1rem;
}

.form-group {
  margin-bottom: 1.5rem;
}

.input-group {
  position: relative;
  display: flex;
  align-items: center;
  border: 2px solid #e5e7eb;
  border-radius: 12px;
  transition: all 0.3s ease;
  overflow: hidden;
}

.input-group:focus-within {
  border-color: #1890ff;
  box-shadow: 0 0 0 3px rgba(24, 144, 255, 0.1);
}

.input-icon {
  padding: 0 1rem;
  color: #9ca3af;
}

input {
  width: 100%;
  padding: 0.75rem;
  background: transparent;
  border: none;
  font-size: 1rem;
  color: #1f2937;
  outline: none;
}

input::placeholder {
  color: #9ca3af;
}

.code-group {
  display: flex;
  align-items: stretch;
  position: relative;
}

.code-group input {
  padding-left: 4rem;
  flex: 1;
}

.code-group .input-icon {
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  padding: 0 1rem;
  color: #9ca3af;
  display: flex;
  align-items: center;
  pointer-events: none;
}

.code-group .input-icon svg {
  margin-top: 2px;
}

.code-btn {
  min-width: 120px;
  padding: 0.75rem 1rem;
  background: #f3f4f6;
  border: none;
  border-left: 2px solid #e5e7eb;
  color: #1890ff;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  border-radius: 0 10px 10px 0;
}

.code-btn:hover:not(:disabled) {
  background: #e5e7eb;
}

.code-btn:disabled {
  color: #9ca3af;
  cursor: not-allowed;
}

.submit-btn {
  width: 100%;
  padding: 1rem;
  background: #343a40;
  color: white;
  border: none;
  border-radius: 12px;
  font-size: 1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-top: 2rem;
}

.submit-btn:hover:not(:disabled) {
  background: #212529;
}

.submit-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

.error-message {
  color: #dc2626;
  font-size: 0.875rem;
  margin-top: 0.5rem;
  display: block;
}

.bottom-links {
  margin-top: 2rem;
  text-align: center;
}

.back-link {
  color: #1890ff;
  text-decoration: none;
  font-weight: 500;
  font-size: 0.9rem;
}

.back-link:hover {
  text-decoration: underline;
}

.brand {
  margin-bottom: 2rem;
}

.brand .logo {
  font-size: 2rem;
  font-weight: bold;
  color: #343a40;
  margin-bottom: 1rem;
}

.brand h1 {
  font-size: 2rem;
  color: #343a40;
  margin-bottom: 0.5rem;
}

.brand .slogan {
  color: #6b7280;
  font-size: 1.1rem;
}

.password-tip {
  margin-top: 0.5rem;
  padding: 0.5rem;
  background: #f8f9fa;
  border-radius: 8px;
  font-size: 0.9rem;
  color: #6b7280;
}

.password-tip p {
  margin: 0 0 0.5rem 0;
  font-weight: 500;
}

.password-tip ul {
  list-style: none;
  margin: 0;
  padding: 0;
}

.password-tip li {
  margin: 0.2rem 0;
  color: #9ca3af;
}

.password-tip li.valid {
  color: #10b981;
}

.input-group:focus-within + .password-tip {
  border: 1px solid #e5e7eb;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

@media (max-width: 1024px) {
  .login-box {
    width: 800px;
  }
  
  .login-right {
    padding: 40px;
  }
}

@media (max-width: 768px) {
  .login-left {
    display: none;
  }
  
  .login-box {
    width: 100%;
    max-width: 500px;
  }
}
</style> 